package adger.me.yili.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import net.soulwolf.widget.speedyselector.widget.SelectorEditText;
import net.soulwolf.widget.speedyselector.widget.SelectorTextView;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;

import adger.me.yili.R;
import adger.me.yili.bean.ConfirmBackBean;
import adger.me.yili.bean.ConfirmBean;
import adger.me.yili.bean.OrdersBeanTable;
import adger.me.yili.utils.Arith;
import adger.me.yili.utils.DB;
import adger.me.yili.utils.SharePreferencesUtil;
import adger.me.yili.utils.StrUtil;
import adger.me.yili.utils.UriCenter;
import adger.me.yili.utils.XHttp;
import adger.me.yili.view.CommonAdapter;
import adger.me.yili.view.ViewHolder;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailMActivity extends AppCompatActivity {

    @Bind(R.id.ll_menu_left)
    LinearLayout ll_menu_left;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.lv_orders)
    ListView lv_orders;
    @Bind(R.id.set_totalMoney)
    SelectorEditText set_totalMoney;
    @Bind(R.id.stv_linqu)
    SelectorTextView stv_linqu;
    @Bind(R.id.stv_yilinquOryituihuo)
    SelectorTextView stv_yilinquOryituihuo;
    @Bind(R.id.stv_tuihuo)
    SelectorTextView stv_tuihuo;
    @Bind(R.id.ll_state)
    LinearLayout ll_state;
    @Bind(R.id.tv_songhuo)
    TextView tv_songhuo;
    @Bind(R.id.tv_menu_rightTitle)
    TextView tv_menu_rightTitle;
    private List<OrdersBeanTable.OrdersEntity.OrderLinesEntity> mDatas = new ArrayList<OrdersBeanTable.OrdersEntity.OrderLinesEntity>();
    private CommonAdapter<OrdersBeanTable.OrdersEntity.OrderLinesEntity> mAdapter;
    private OrdersBeanTable.OrdersEntity ordersEntity;
    Boolean inputFinish = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_login);
        setContentView(R.layout.activity_order_detail2);
        ButterKnife.bind(this);
        String ordersEntityStr = getIntent().getStringExtra("ordersEntityStr");
        ordersEntity = new Gson().fromJson(ordersEntityStr, OrdersBeanTable.OrdersEntity.class);
        try {
            DbManager dbManager = DB.getXInstance();
            List<OrdersBeanTable.OrdersEntity.OrderLinesEntity> orderLinesEntityList = dbManager.selector(OrdersBeanTable.OrdersEntity.OrderLinesEntity.class).where("partent_id", "=", ordersEntity.getId()).findAll();
            mDatas.addAll(orderLinesEntityList);
        } catch (DbException e) {
            e.printStackTrace();
        }

        setAdapter();
        initView();
    }

    private void initView() {

        title.setText(SharePreferencesUtil.getSpString("curryGroup_no", "", this) + "期 订单详情");
        if (ordersEntity.getDeliver() == 1) {//送货
            tv_songhuo.setVisibility(View.VISIBLE);
        }
        if (ordersEntity.getConfirmed() == 1)//已领取
        {
            ll_state.setVisibility(View.GONE);
            stv_yilinquOryituihuo.setVisibility(View.VISIBLE);
            if (ordersEntity.getClaimed() == 0)//退货了
            {
                stv_yilinquOryituihuo.setText("已退货");
            } else {//==1  已经领取
                tv_menu_rightTitle.setBackgroundColor(Color.parseColor("#E57918"));
                tv_menu_rightTitle.setText("修改");
            }
        }//未领取 不变
    }

    private void setAdapter() {

        //mdatas 记得加数据进去
        mAdapter = new CommonAdapter<OrdersBeanTable.OrdersEntity.OrderLinesEntity>(this, mDatas, R.layout.orderdetail_item) {


            @Override
            public void convert(ViewHolder helper, int position, OrdersBeanTable.OrdersEntity.OrderLinesEntity item) {
                helper.setText(R.id.tv_produce_first, item.getName());
                helper.setText(R.id.tv_unit_first, item.getPrice() + "元/" + item.getUnit());
                helper.setText(R.id.set_first, item.getQuantity() + "");
                helper.setText(R.id.tv_buy_unit, item.getBuy_unit());
                helper.setText(R.id.set_firstTotal, item.getCharge() + "");
                helper.setOnclickListener(R.id.iv_reduce, new MyListener(helper, position, item));
                helper.setOnclickListener(R.id.iv_add, new MyListener(helper, position, item));
                MyTextWatcher watcher = new MyTextWatcher(helper, position, item);
                helper.getView(SelectorEditText.class, R.id.set_first).addTextChangedListener(watcher);//把所有的都添加进监听器
                if (item.getWeighable() == 1) {//手动输入
                    helper.setEnable(R.id.set_firstTotal, true);
                    helper.getView(SelectorEditText.class, R.id.set_first).removeTextChangedListener(watcher);//去掉满足条件的一个
                    SelectorEditText set_firstTotal = helper.getView(SelectorEditText.class, R.id.set_firstTotal);
//                    set_firstTotal.addTextChangedListener(new MyEnableTextWatcher(helper, position, item,set_firstTotal));//把所有的都添加进监听器
                    set_firstTotal.setOnFocusChangeListener(new MyEnableTextWatcher(helper, position, item, set_firstTotal));//把所有的都添加进监听器
                    if (set_firstTotal.getText().toString().equals("-1.0")) {
                        set_firstTotal.setText("");
                    }
                }
            }
        };
        View orderdetail_header = getLayoutInflater().inflate(R.layout.orderdetail_header, null);
        TextView detail_username = (TextView) ButterKnife.findById(orderdetail_header, R.id.detail_username);
        TextView detail_order_number = (TextView) ButterKnife.findById(orderdetail_header, R.id.detail_order_number);
        TextView detail_phone = (TextView) ButterKnife.findById(orderdetail_header, R.id.detail_phone);
        TextView detail_address = (TextView) ButterKnife.findById(orderdetail_header, R.id.detail_address);
        ImageView iv_intent_call = (ImageView) ButterKnife.findById(orderdetail_header, R.id.iv_intent_call);
        iv_intent_call.setOnClickListener(new MyListener());
        detail_username.setText(ordersEntity.getUser());
        detail_order_number.setText(ordersEntity.getUser_sn());
        detail_phone.setText(ordersEntity.getTelephone());
        detail_address.setText(ordersEntity.getAddress());
        lv_orders.addHeaderView(orderdetail_header);
        lv_orders.setAdapter(mAdapter);
        calculateAllCharge();
    }

    @OnClick({R.id.stv_linqu, R.id.stv_tuihuo,R.id.tv_menu_rightTitle})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.stv_linqu:
                updateLinQuState(1);
                break;
            case R.id.stv_tuihuo:
                updateLinQuState(0);
                break;
            case R.id.tv_menu_rightTitle:
                ll_state.setVisibility(View.VISIBLE);
                stv_yilinquOryituihuo.setVisibility(View.GONE);
                break;
        }
    }

    private void updateLinQuState(final int i) {
        if (inputFinish == false) {
            Toast.makeText(this, "请输入称重商品的金额", Toast.LENGTH_SHORT).show();
            return;
        }
        ConfirmBean confirmBean = new ConfirmBean();
        confirmBean.setToken(SharePreferencesUtil.getSpString("histryToken", "", this));
        confirmBean.setOrder_id(Integer.parseInt(ordersEntity.getId()));
        confirmBean.setClaimed(i);
        if (i == 0) {
            confirmBean.setCharge(0);
        } else {
            if (!TextUtils.isEmpty(set_totalMoney.getText().toString().trim())) {
                confirmBean.setCharge(Float.parseFloat(set_totalMoney.getText().toString().trim()));
                List<ConfirmBean.OrderLinesBean> beanList = new ArrayList<>();
                for (OrdersBeanTable.OrdersEntity.OrderLinesEntity item : mDatas) {
                    ConfirmBean.OrderLinesBean bean = new ConfirmBean.OrderLinesBean();
                    bean.setCharge(item.getCharge());
                    bean.setQuantity(item.getQuantity());
                    bean.setId(Integer.parseInt(item.getId()));
                    beanList.add(bean);
                }
                confirmBean.setOrder_lines(beanList);
            }
        }
        Logger.d(confirmBean.getCharge() + "......");
        XHttp.post(UriCenter.confirm, confirmBean, new XHttp.XCallback<ConfirmBackBean>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onSuccess(ConfirmBackBean bean) {
                if (bean.getError() == 0) {
                    //更新本地数据
                    Toast.makeText(OrderDetailMActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
                    DbManager dbManager = DB.getXInstance();
                    ordersEntity.setConfirmed(1);
                    ordersEntity.setClaimed(i);
                    if (i == 1) {
                        ordersEntity.setCharge(Float.parseFloat(set_totalMoney.getText().toString()));
                    }
                    try {
                        Logger.d("保存之前");
                        dbManager.saveOrUpdate(ordersEntity);//跟新操作 第三层
                        dbManager.saveOrUpdate(mDatas);//TODO
                        //测试
//                        OrdersBeanTable.OrdersEntity entity=   dbManager.selector(OrdersBeanTable.OrdersEntity.class).where("user_sn", "=", "0429").findFirst();
//                        Logger.d("保存成功 entity update after ------Confirmed->"+ entity.getConfirmed()+"    Claimed"+entity.getClaimed());
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
//                    MainActivity.mInstance.update();//更新网络数据
                    finish();
                } else {
                    Toast.makeText(OrderDetailMActivity.this, bean.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @OnClick(R.id.ll_menu_left)
    public void onClick() {
        finish();
    }

    private class MyTextWatcher implements TextWatcher {
        ViewHolder helper;
        int position;
        OrdersBeanTable.OrdersEntity.OrderLinesEntity item;

        MyTextWatcher(ViewHolder helper, int position, OrdersBeanTable.OrdersEntity.OrderLinesEntity item) {
            this.helper = helper;
            this.position = position;
            this.item = item;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable edt) {
//            Toast.makeText(OrderDetailMActivity.this, "afterTextChanged", Toast.LENGTH_SHORT).show();
            Logger.d(position + "   afterTextChanged");
            float itemTotal = item.getPrice() * item.getQuantity();
            String resultValueStr = StrUtil.formateRate(itemTotal + "");
            item.setCharge(Float.valueOf(resultValueStr));
            calculateAllCharge();
            mAdapter.notifyDataSetChanged();
        }
    }

    private class MyEnableTextWatcher implements View.OnFocusChangeListener {
        ViewHolder helper;
        int position;
        OrdersBeanTable.OrdersEntity.OrderLinesEntity item;
        SelectorEditText set_firstTotal;

        MyEnableTextWatcher(ViewHolder helper, int position, OrdersBeanTable.OrdersEntity.OrderLinesEntity item, SelectorEditText set_firstTotal) {
            this.helper = helper;
            this.position = position;
            this.item = item;
            this.set_firstTotal = set_firstTotal;
        }


        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
            } else {
                // 此处为失去焦点时的处理内容
                Logger.d("  Enable " + position);
                String str = set_firstTotal.getText().toString().replace("-", "");
                if (str.endsWith(".")) {
                    str = str.substring(0, str.length() - 1);
                }
                Logger.d(str);
                String resultValueStr = StrUtil.formateRate(str);
                if (resultValueStr.equals("")) {
                    return;
                }
                item.setCharge(Float.valueOf(resultValueStr));
                inputFinish = true;
                calculateAllCharge();
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 计算总和
     */
    private void calculateAllCharge() {
        float allItemCharge = 0;
        for (OrdersBeanTable.OrdersEntity.OrderLinesEntity orderLinesEntity : mDatas) {

            if (orderLinesEntity.getCharge() == -1.0) {
                inputFinish = false;
            } else {
                allItemCharge = Arith.add(allItemCharge, orderLinesEntity.getCharge());
            }

//            if (orderLinesEntity.getWeighable() == 1&&orderLinesEntity.getCharge() == -1.0) {//称重商品,并且没有输入金额
//                    inputFinish=false;
//            }
//            else {
//                allItemCharge=Arith.add(allItemCharge, orderLinesEntity.getCharge());
//            }
        }

        set_totalMoney.setText(StrUtil.formateRate(allItemCharge + ""));
    }

    private class MyListener implements View.OnClickListener {
        ViewHolder helper;
        int position;
        OrdersBeanTable.OrdersEntity.OrderLinesEntity item;

        MyListener() {

        }

        MyListener(ViewHolder helper, int position, OrdersBeanTable.OrdersEntity.OrderLinesEntity item) {
            this.helper = helper;
            this.position = position;
            this.item = item;
        }

        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.iv_reduce:
                    int tempInt = item.getQuantity() - 1;
                    if (tempInt > -1) {
                        item.setQuantity(tempInt);//设置进实体类
                        mAdapter.notifyDataSetChanged();
                    }
                    break;
                case R.id.iv_add:
                    int tempAddInt = item.getQuantity() + 1;
                    item.setQuantity(tempAddInt);//设置进实体类
                    mAdapter.notifyDataSetChanged();
                    break;
                case R.id.lv_orders:
                    break;
                case R.id.iv_intent_call:
                    onCall();
                    break;
            }
        }
    }

    private void startOldCall() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.CALL");
        intent.setData(Uri.parse("tel:" + ordersEntity.getTelephone()));//mobile为你要拨打的电话号码，模拟器中为模拟器编号也可
        startActivity(intent);
    }

    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;

    public void onCall() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_ASK_CALL_PHONE);
                return;
            } else {
                //上面已经写好的拨号方法
                startOldCall();
            }
        } else {
            //上面已经写好的拨号方法
            startOldCall();
        }
    }
}
